new Vue({
    el: '#app',
    data() {
        return {
            form: { PageNumber: 1, RowAmount: 20 },
            list: [],
            total: 0,
            pageAcquisition: null,
            // 单位映射与收货单位显示
            unitMap: {},
            receiveUnitText: '单位',

            // 付款弹窗
            dialogPayVisible: false,
            paySaving: false,
            payContext: null,
            payForm: { amount: '', Picture_URL: '' },

            // 收货弹窗
            dialogReceiveVisible: false,
            receiveSaving: false,
            receiveContext: null,
            receiveForm: { receiptQuantity: '' },
            receiveView: null,
            receiveLogisticsList: [],

        }
    },
    mounted() { this.getList(); },
    methods: {
        async getList() {
            try {
                const params = new URLSearchParams(location.search);
                const orderSerial = params.get('orderSerial') || '';
                const cond = orderSerial ? `Acquisition_Order_SerialNumber='${orderSerial.replace(/'/g, "''")}'` : '';
                const res = await generalApi.generalQueryByTableName({ Data: 'acquisition_order', Condition: cond });
                const arr = Array.isArray(res) ? res : (res.Data || []);
                this.list = arr || [];
                // 为每条记录预先初始化阶段数组，避免后续新增属性不响应
                try {
                    (this.list || []).forEach((row, idx) => {
                        if (!row) return;
                        // 使用 Vue 响应式设置
                        if (typeof this.$set === 'function') {
                            this.$set(this.list[idx], '_stagePaymentsFixed', []);
                        } else {
                            this.list[idx]._stagePaymentsFixed = [];
                        }
                    });
                } catch (e) { /* ignore init error */ }
                this.total = (this.list || []).length;
                // 顶部原信息
                if (this.list && this.list[0] && this.list[0].Acquisition_Unit_Price_SerialNumber) {
                    const up = await generalApi.generalQueryByTableName({
                        Data: 'acquisition_unitprice',
                        Condition: `Acquisition_Unit_Price_SerialNumber='${String(this.list[0].Acquisition_Unit_Price_SerialNumber).replace(/'/g, "''")}'`
                    });
                    this.pageAcquisition = (Array.isArray(up) ? up[0] : (up && up.Data && up.Data[0])) || null;
                    // 设置收货单位文本
                    await this.loadUnitMap();
                    try {
                        const txt = this.getUnitText(this.pageAcquisition && this.pageAcquisition.Article_Unit_SerialNumber);
                        this.receiveUnitText = (txt && String(txt).trim()) || '单位';
                    } catch (e) { this.receiveUnitText = '单位'; }
                }
                // 绑定阶段付款信息
                await this.bindStages();
            } catch (e) { console.error(e); }
        },
        async loadUnitMap() {
            try {
                const serials = [];
                if (this.pageAcquisition && this.pageAcquisition.Article_Unit_SerialNumber) {
                    serials.push(this.pageAcquisition.Article_Unit_SerialNumber);
                }
                const set = [...new Set(serials.filter(Boolean))];
                if (set.length === 0) { this.unitMap = {}; return; }
                const unitRes = await generalApi.generalQueryByTableName({
                    Data: 'article_unit',
                    Condition: `Article_Unit_SerialNumber IN (${set.map(u => `'${String(u).replace(/'/g, "''")}'`).join(',')})`
                });
                const unitArr = Array.isArray(unitRes) ? unitRes : (unitRes.Data || []);
                const map = {};
                (unitArr || []).forEach(u => { if (u.Article_Unit_SerialNumber) map[u.Article_Unit_SerialNumber] = u.Unit; });
                this.unitMap = map;
            } catch (e) { this.unitMap = {}; }
        },
        getUnitText(serial) {
            const s = String(serial || '').trim();
            if (!s) return '';
            return this.unitMap[s] || s;
        },
        // 格式化地址（省市区+详细地址）
        formatAddress(s) {
            if (!s) return '';
            const p = s.ProvinceNumber || '';
            const c = s.CityNumber || '';
            const d = s.CountyNumber || '';
            const a = s.Detailed_Address || '';
            return `${p}${c}${d}${a}`;
        },
        async bindStages() {
            const orders = this.list || [];
            const stageOrder = ['定金', '发货', '到货', '尾款'];
            for (const row of orders) {
                // 1) 读取订单阶段记录
                const cond = `Acquisition_Order_SerialNumber='${String(row.Acquisition_Order_SerialNumber||'').replace(/'/g, "''")}'`;
                const res = await generalApi.generalQueryByTableName({ Data: 'acquisition_order_paystages', Condition: cond });
                const stages = Array.isArray(res) ? res : (res.Data || []);

                // 2) 读取报价侧阶段方案百分比
                const percentMap = {};
                const schemeMap = {};
                try {
                    const unitSerial = String(row.Acquisition_Unit_Price_SerialNumber || '').trim();
                    if (unitSerial) {
                        const spRes = await generalApi.generalQueryByTableName({
                            Data: 'acquisition_unitprice_staged_payment',
                            Condition: `Acquisition_Unit_Price_SerialNumber='${unitSerial.replace(/'/g, "''")}'`
                        });
                        const spArr = Array.isArray(spRes) ? spRes : (spRes && spRes.Data) || [];
                        (spArr || []).forEach(sp => {
                            const name = String(sp.Stage_Name || '').trim();
                            const schemeSerial = String(sp.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '').trim();
                            if (name) percentMap[name] = sp.Percent;
                            if (schemeSerial) schemeMap[schemeSerial] = { name, percent: sp.Percent };
                        });
                    }
                } catch (e) { /* ignore */ }

                // 3) 构建字典并映射金额字段（优先 Due_Amount）
                const stageDict = {};
                for (const st of (stages || [])) {
                    const schemeSerial = String(st.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '').trim();
                    const fallback = schemeSerial ? schemeMap[schemeSerial] : null;
                    const name = String(st.Stage_Name || (fallback && fallback.name) || '').trim();
                    if (!name) continue;
                    const percent = (fallback && fallback.percent !== undefined && fallback.percent !== null && fallback.percent !== '')
                        ? fallback.percent
                        : (percentMap[name] !== undefined ? percentMap[name] : '');
                    const dueRaw = (st.Due_Amount !== undefined && st.Due_Amount !== null && st.Due_Amount !== '')
                        ? Number(st.Due_Amount) : ((st.Trading_Amount !== undefined && st.Trading_Amount !== null && st.Trading_Amount !== '') ? Number(st.Trading_Amount) : '');
                    const paidRaw = (st.Paid_Amount !== undefined && st.Paid_Amount !== null && st.Paid_Amount !== '')
                        ? Number(st.Paid_Amount) : 0;
                    const remainRaw = (st.Remain_Amount !== undefined && st.Remain_Amount !== null && st.Remain_Amount !== '')
                        ? Number(st.Remain_Amount) : (dueRaw !== '' ? Number((dueRaw - paidRaw).toFixed(2)) : 0);
                    const collectedRaw = (st.Collection_Amount !== undefined && st.Collection_Amount !== null && st.Collection_Amount !== '')
                        ? Number(st.Collection_Amount) : 0;
                    const unCollectedRaw = (st.Unamount !== undefined && st.Unamount !== null && st.Unamount !== '')
                        ? Number(st.Unamount) : (dueRaw !== '' ? Number((dueRaw - collectedRaw).toFixed(2)) : 0);
                    stageDict[name] = {
                        serial: st.Acquisition_Order_Paystages_SerialNumber,
                        stage: name,
                        percent: (percent !== '' ? percent : (percentMap[name] !== undefined ? percentMap[name] : '')),
                        payWindow: this.formatPayWindow(st.Start_Datetime, st.End_Datetime),
                        // 买方：展示应付/已付/未付
                        dueAmount: (dueRaw !== '' ? String(dueRaw) : ''),
                        paidAmount: String(paidRaw),
                        unpaidAmount: String(remainRaw),
                        Pay_Status: st.Pay_Status,
                        Receipt_Pay_Status: st.Receipt_Pay_Status,
                        Ship_Status: st.Ship_Status,
                        Receipt_Ship_Status: st.Receipt_Ship_Status
                    };
                }

                // 4) 固定渲染四阶段，缺失时用百分比与订单金额回显
                const fixed = stageOrder.map(name => {
                    const s = stageDict[name] || {};
                    let fbDue = '';
                    let fbUnpaid = 0;
                    try {
                        const p = Number((s.percent !== undefined && s.percent !== null && s.percent !== '') ? s.percent : (percentMap[name] || ''));
                        const amt = Number(row.Amount || 0);
                        if (Number.isFinite(p) && Number.isFinite(amt) && p > 0 && amt > 0) {
                            const calc = Number(((amt * p) / 100).toFixed(2));
                            fbDue = String(calc);
                            fbUnpaid = calc;
                        }
                    } catch (e) { /* ignore */ }
                    return {
                        serial: s.serial || '',
                        stage: name,
                        percent: (s.percent !== undefined && s.percent !== null && s.percent !== '') ? s.percent : ((percentMap[name] !== undefined && percentMap[name] !== null && percentMap[name] !== '') ? percentMap[name] : ''),
                        payWindow: (s.payWindow !== undefined && s.payWindow !== null) ? s.payWindow : '',
                        dueAmount: (s.dueAmount !== undefined && s.dueAmount !== null && s.dueAmount !== '') ? s.dueAmount : fbDue,
                        paidAmount: (s.paidAmount !== undefined && s.paidAmount !== null) ? s.paidAmount : '0',
                        unpaidAmount: (s.unpaidAmount !== undefined && s.unpaidAmount !== null) ? s.unpaidAmount : String(fbUnpaid),
                        // 操作状态（缺省为 0 可操作）
                        Pay_Status: (s.Pay_Status !== undefined && s.Pay_Status !== null && s.Pay_Status !== '') ? String(s.Pay_Status) : '0',
                        Receipt_Pay_Status: (s.Receipt_Pay_Status !== undefined && s.Receipt_Pay_Status !== null && s.Receipt_Pay_Status !== '') ? String(s.Receipt_Pay_Status) : '0',
                        Ship_Status: (s.Ship_Status !== undefined && s.Ship_Status !== null && s.Ship_Status !== '') ? String(s.Ship_Status) : '0',
                        Receipt_Ship_Status: (s.Receipt_Ship_Status !== undefined && s.Receipt_Ship_Status !== null && s.Receipt_Ship_Status !== '') ? String(s.Receipt_Ship_Status) : '0'
                    };
                });
                // 使用响应式赋值，确保表格正确渲染
                if (typeof this.$set === 'function') {
                    this.$set(row, '_stagePaymentsFixed', fixed);
                } else {
                    row._stagePaymentsFixed = fixed;
                }
            }
        },
        formatPayWindow(start, end) { const s = start || ''; const e = end || ''; return (s && e) ? `${s} ~ ${e}` : ''; },
        contractStatusTagType(st) { const v = String(st||''); if (v==='11') return 'success'; if (v==='10' || v==='01') return 'warning'; return 'info'; },
        formatContractStatus(st) { const v = String(st||''); if (v==='11') return '双方已确认'; if (v==='10') return '买方已确认'; if (v==='01') return '卖方已确认'; return '双方未确认'; },
        // 双方确认后才视为已确认
        isContractConfirmed(row) { return String((row && row.Contract_Status) || '') === '11'; },
        actionEnabled(stageRow, type) {
            if (!stageRow) return false;
            const payStatus = String(stageRow.Pay_Status || '');
            const receiptShipStatus = String(stageRow.Receipt_Ship_Status || '');
            const receiptPayStatus = String(stageRow.Receipt_Pay_Status || '');
            // 付款：已付满或未付为0则置灰
            if (type === 'pay') {
                const unpaidNum = Number(stageRow.unpaidAmount || 0);
                if (payStatus === '1') return false;
                if (Number.isFinite(unpaidNum) && unpaidNum <= 0) return false;
                return true;
            }
            // 收货：已置灰（收满）则不可操作
            if (type === 'receive') {
                if (receiptShipStatus === '1') return false;
                return true;
            }
            // 收发票：已完成则不可操作
            if (type === 'receipt_invoic') {
                if (receiptPayStatus === '1') return false;
                return true;
            }
            return true;
        },

        // 买方确认合同：依据当前状态计算下一个状态并保存到 acquisition_order
        async confirmByA(row) {
            try {
                const curr = String((row && row.Contract_Status) || '00');
                if (curr === '10' || curr === '11') { this.$message.info('买方已确认，无需重复操作'); return; }
                const next = (curr === '01') ? '11' : '10';

                const arr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'acquisition_order',
                    Condition: `Acquisition_Order_SerialNumber='${String(row.Acquisition_Order_SerialNumber||'').replace(/'/g, "''")}'`
                });
                const orderRow = Array.isArray(arr) ? arr[0] : (arr && arr.Data && arr.Data[0]);
                if (!orderRow) { this.$message.error('未找到订单或存在重复记录'); return; }
                const now = getYMDHMSDate();
                const creator = (typeof getCookie === 'function') ? (getCookie('user') || '') : '';
                const od = { ...orderRow, Contract_Status: next, Operation_ID: creator, Operation_Datetime: now };
                const dataset = { Modify: { acquisition_order: [od] }, Add: { } };
                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    row.Contract_Status = next;
                    this.$message.success(next === '11' ? '双方已确认合同' : '买方已确认合同');
                    await this.getList();
                } else { const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败'; this.$message.error(msg); }
            } catch (e) { this.$message.error('买方确认失败，请稍后再试'); }
        },
        // 付款弹窗
        openPayDialog(orderRow, stageRow) { this.payContext = { order: orderRow, stage: stageRow }; this.payForm = { amount: '', Picture_URL: '' }; this.dialogPayVisible = true; },
        //付款提交
        async confirmPay() {
            if (!this.payContext || !this.payContext.order) { this.$message.error('上下文缺失，无法付款'); return; }
            const order = this.payContext.order;
            const stage = this.payContext.stage || {};
            const amountNum = Number(this.payForm.amount || 0);
            if (!Number.isFinite(amountNum) || amountNum <= 0) { this.$message.error('请输入有效的付款金额'); return; }
            this.paySaving = true;
            try {
                // 1) 查询订单原值以便累计 Paid_Amount / Remain_Amount
                const orderArr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'acquisition_order',
                    Condition: `Acquisition_Order_SerialNumber='${String(order.Acquisition_Order_SerialNumber||'').replace(/'/g, "''")}'`
                });
                const od = Array.isArray(orderArr) ? orderArr[0] : (orderArr && orderArr.Data && orderArr.Data[0]);
                if (!od) { this.$message.error('未找到订单'); this.paySaving=false; return; }
                const oldPaid = Number(od.Paid_Amount || 0);
                const newPaid = accAdd(oldPaid, amountNum);
                od.Paid_Amount = String(newPaid);
                const orderTotalAmountNum = Number(order.Amount || 0);
                const newRemainNum = Number((orderTotalAmountNum - newPaid).toFixed(2));
                od.Remain_Amount = String(newRemainNum >= 0 ? newRemainNum : 0);

                // 2) 查询当前阶段付款记录：累计并防止超付
                let stageModify = null;
                const totalAmount = Number(order.Amount || 0);
                const hasPercent = !(stage.percent === undefined || stage.percent === null || stage.percent === '');
                const percentVal = hasPercent ? Number(stage.percent) : NaN;
                const tradingAmountNum = (Number.isFinite(totalAmount) && hasPercent && Number.isFinite(percentVal))
                    ? Number((totalAmount * percentVal / 100).toFixed(2))
                    : Number((stage.dueAmount !== undefined && stage.dueAmount !== null && stage.dueAmount !== '' ? stage.dueAmount : 0));
                
                if (!stage.serial) { this.$message.error('缺少阶段标识，无法付款'); this.paySaving=false; return; }
                const condStr = `Acquisition_Order_Paystages_SerialNumber='${String(stage.serial).replace(/'/g, "''")}'`;
                const stageArr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'acquisition_order_paystages',
                    Condition: condStr
                });
                if (!Array.isArray(stageArr) || stageArr.length < 1) { this.$message.error('付款阶段不存在，无法操作'); this.paySaving=false; return; }
                stageModify = stageArr[0];
                const sOld = Number(stageModify.Paid_Amount || 0);
                const targetTrading = Number(stageModify.Trading_Amount || tradingAmountNum || 0);
                if (Number.isFinite(targetTrading) && targetTrading > 0 && accAdd(sOld, amountNum) > targetTrading) {
                    this.$message.error('付款金额超出本阶段应付'); this.paySaving=false; return; }
                const newStagePaid = accAdd(sOld, amountNum);
                stageModify.Paid_Amount = String(newStagePaid);
                if (Number.isFinite(targetTrading)) {
                    const remainStage = Math.max(Number((targetTrading - newStagePaid).toFixed(2)), 0);
                    stageModify.Remain_Amount = String(remainStage);
                }
                if (!stageModify.Enterprise_Info_SerialNumber) { stageModify.Enterprise_Info_SerialNumber = getCookie('enterprise'); }
                if (Number.isFinite(tradingAmountNum)) stageModify.Trading_Amount = String(tradingAmountNum);
                const nowStr = getYMDHMSDate();
                stageModify.Collection_Date = nowStr;
                stageModify.Paid_Datetime = nowStr;
                stageModify.Pay_Status = (Number.isFinite(targetTrading) && targetTrading > 0 && newStagePaid >= targetTrading) ? '1' : '0';

                const supplierSerial = (this.pageAcquisition && this.pageAcquisition.Enterprise_Info_SerialNumber) ? this.pageAcquisition.Enterprise_Info_SerialNumber : (this.enterpriseId || '');
                // 传入到 payment 的阶段应付金额
                const stagePayableAmount = (Number.isFinite(targetTrading) && targetTrading > 0)
                    ? targetTrading
                    : (Number.isFinite(tradingAmountNum) && tradingAmountNum > 0 ? tradingAmountNum : 0);
                const dataset = { Modify: { acquisition_order: [od], acquisition_order_paystages: [stageModify] }, Add: { payment: this.getPayment(amountNum, stage.serial, (this.payForm && this.payForm.Picture_URL) ? this.payForm.Picture_URL : '', supplierSerial, stagePayableAmount) } };
                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('付款成功');
                    this.dialogPayVisible = false;
                    this.getList();
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) {
                this.$message.error('付款失败，请稍后再试');
            } finally { this.paySaving = false; }
        },
        getPayment(Amount, Business_Order_SerialNumber, Payment_Voucher_Picture, Supplier_SerialNumber, StageAmount) {
            const stageAmtNum = Number(StageAmount);
            return [{
                Supplier_SerialNumber: Supplier_SerialNumber || '',
                Payment_Date: getYMDHMSDate(),
                Payment_Amount: String(Amount),
                // 该阶段应付金额，确保为有效数值
                Amount: (Number.isFinite(stageAmtNum) ? String(stageAmtNum) : '0'),
                Bank_Voucher_SerialNumber: '',
                Enterprise_Info_SerialNumber: getCookie('enterprise'),
                Children: {
                    payment_detail: [{
                        Business_Order_SerialNumber: Business_Order_SerialNumber,
                        Payment_Method: '电子汇款',
                        Payment_Type: '0',
                        Amount: String(Amount),
                        Enterprise_Info_SerialNumber: getCookie('enterprise')
                    }],
                    payment_voucher: [{
                        Payment_Voucher_Picture: Payment_Voucher_Picture,
                        Enterprise_Info_SerialNumber: getCookie('enterprise')
                    }]
                }
            }]
        },

        // 收货查看与确认
        async openReceiveDialog(orderRow, stageRow) {
            try {
                const list = await generalApi.generalQueryByTableName({
                    Data: 'acquisition_order_logistics',
                    // 买方页面按采购订单号查询物流
                    Condition: `Acquisition_Order_SerialNumber='${String(orderRow.Acquisition_Order_SerialNumber||'').replace(/'/g,"''")}'`
                });
                const arr = Array.isArray(list) ? list : (list.Data || []);

                // 反查物流公司名称（批量查询并映射）
                let nameMap = {};
                try {
                    const codes = [...new Set((arr || []).map(it => it.Logistics_Code).filter(Boolean))];
                    if (codes.length) {
                        const con = `Logistics_Code IN (${codes.map(c => `'${String(c).replace(/'/g,"''")}'`).join(',')})`;
                        const opts = await generalApi.generalQueryByTableName({ Data: 'logistics_info', Condition: con });
                        const oa = Array.isArray(opts) ? opts : (opts.Data || []);
                        (oa || []).forEach(o => { nameMap[o.Logistics_Code] = o.Logistics_Name; });
                    }
                } catch (e) {}

                // 组装列表并兼容图片地址
                const listMap = (arr || []).map(it => {
                    const item = Object.assign({}, it);
                    if (item && item.Logistics_Code) item.Logistics_Name = nameMap[item.Logistics_Code] || item.Logistics_Name || '';
                    if (item && item.Picture_URL && !(String(item.Picture_URL).startsWith('http'))) {
                        item.Picture_URL = (typeof imageApi !== 'undefined' ? imageApi : '') + item.Picture_URL;
                    }
                    return item;
                });
                this.receiveLogisticsList = listMap;

                // 选择最新的一条用于图片展示
                let rec = arr && arr[0];
                if (arr && arr.length > 1) {
                    rec = arr.slice().sort((a,b)=> new Date(b.Create_Datetime||0) - new Date(a.Create_Datetime||0))[0];
                }
                if (rec && rec.Logistics_Code) rec.Logistics_Name = nameMap[rec.Logistics_Code] || rec.Logistics_Name;
                if (rec && rec.Picture_URL && !(String(rec.Picture_URL).startsWith('http'))) {
                    rec.Picture_URL = (typeof imageApi !== 'undefined' ? imageApi : '') + rec.Picture_URL;
                }

                this.receiveView = rec || null;
                this.receiveContext = { order: orderRow, stage: stageRow };
                this.receiveForm = { receiptQuantity: '' };

                // 单位文案（买方：从 acquisition 获取单位）
                try {
                    const serial = (orderRow && orderRow.Article_Unit_SerialNumber)
                        || (orderRow && orderRow.originAcquisition && orderRow.originAcquisition.Article_Unit_SerialNumber)
                        || (this.pageAcquisition && this.pageAcquisition.Article_Unit_SerialNumber)
                        || '';
                    const txt = this.getUnitText(serial);
                    this.receiveUnitText = (txt && String(txt).trim()) || '单位';
                } catch (e) { this.receiveUnitText = '单位'; }

                this.dialogReceiveVisible = true;
            } catch (e) {
                this.$message.error('查询物流信息失败');
            }
        },
        // 收货确认：保存入库数量到 purchase_receipt/purchase_receipt_detail，并同步更新买方订单与阶段
        async onConfirmReceive() {
            try {
                if (!this.receiveContext || !this.receiveContext.order) { this.dialogReceiveVisible=false; return; }
                const order = this.receiveContext.order;
                const stage = (this.receiveContext && this.receiveContext.stage) || {};
                const inputQtyStr = String(this.receiveForm && this.receiveForm.receiptQuantity || '').trim();
                const inputQty = Number(inputQtyStr);
                if (!inputQtyStr || !(Number.isFinite(inputQty)) || inputQty <= 0) {
                    this.$message.error('请输入有效的入库数量');
                    return;
                }
                const condSafeOrder = String(order.Acquisition_Order_SerialNumber || '').replace(/'/g, "''");
                // 交易数量取 acquisition_order.Quantity
                const receiptQuantitysStr = String(order.Quantity || order.Unit_Quantity || '').trim();
                // 商品流水号取自 originAcquisition.Article_SerialNumber
                const articleSerial = (order && order.originAcquisition && order.originAcquisition.Article_SerialNumber)
                    || (this.pageAcquisition && this.pageAcquisition.Article_SerialNumber) || '';
                const purchaseOrderSerial = String(order.Acquisition_Order_SerialNumber || '').trim();

                // 取最新物流记录的凭证图片，作为收货凭证写入明细
                let receiptVoucher = '';
                try {
                    const pic = (this.receiveView && this.receiveView.Picture_URL) || '';
                    if (pic) {
                        const api = (typeof imageApi !== 'undefined' ? imageApi : '');
                        receiptVoucher = (api && String(pic).startsWith(api)) ? String(pic).slice(api.length) : String(pic);
                    }
                } catch (e) { receiptVoucher = ''; }
                const dataset = { Add: { purchase_receipt: this.getConfirmReceive(receiptQuantitysStr, purchaseOrderSerial, articleSerial, inputQtyStr, receiptVoucher), base_operation_log: [] }, Modify: {} };

                // 累加主表收货量并计算未收量：Unreceipt_Quantity = Quantity - Receipt_Quantity（买方：acquisition_order）
                try {
                    const ordArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'acquisition_order',
                        Condition: `Acquisition_Order_SerialNumber='${condSafeOrder}'`
                    });
                    const ordRow = Array.isArray(ordArr) ? ordArr[0] : (ordArr && ordArr.Data && ordArr.Data[0]);
                    if (ordRow) {
                        const oldReceipt = Number(ordRow.Receipt_Quantity || 0);
                        const newReceipt = accAdd(oldReceipt, inputQty);
                        const qtyTotal = Number(ordRow.Quantity || ordRow.Unit_Quantity || 0);
                        const unReceipt = Math.max(0, Number((qtyTotal - newReceipt).toFixed(2)));
                        ordRow.Receipt_Quantity = String(newReceipt);
                        ordRow.Unreceipt_Quantity = String(unReceipt);
                        const nowRec2 = getYMDHMSDate();
                        const creatorRec2 = $.cookie('user') || $.cookie('enterprise') || '';
                        ordRow.Operation_ID = creatorRec2;
                        ordRow.Operation_Datetime = nowRec2;
                        dataset.Modify['acquisition_order'] = [ordRow];
                    }
                } catch (e) { /* ignore */ }

                // 聚合已收货数量，判断是否收满交易数，置灰到货阶段按钮（买方阶段表：acquisition_order_paystages）
                try {
                    const pr = await generalApi.generalQueryByTableName({ Data: 'purchase_receipt_detail', Condition: `Purchase_Order_SerialNumber='${condSafeOrder}'` });
                    const prArr = Array.isArray(pr) ? pr : (pr.Data || []);
                    const already = (prArr || []).reduce((acc, it) => acc + Number(it.Receipt_Quantity || 0), 0);
                    const tradingQty = Number(receiptQuantitysStr || 0);
                    const newTotal = already + inputQty;
                    const shouldGray = Number.isFinite(tradingQty) && tradingQty > 0 && newTotal >= tradingQty;
                    if (stage) {
                        let fullStageRow = null;
                        const stgName = String(stage.stage || '').trim();
                        // 优先按阶段流水号获取“完整原始行”，失败则回退按订单+阶段名
                        if (stage.serial) {
                            try {
                                const curArr = await generalApi.generalQueryByTableNameWithOriginal({
                                    Data: 'acquisition_order_paystages',
                                    Condition: `Acquisition_Order_Paystages_SerialNumber='${String(stage.serial).replace(/'/g, "''")}'`
                                });
                                fullStageRow = Array.isArray(curArr) ? curArr[0] : (curArr && curArr.Data && curArr.Data[0]);
                            } catch (e2) { /* ignore */ }
                        }
                        if (!fullStageRow) {
                            try {
                                const fbArr = await generalApi.generalQueryByTableNameWithOriginal({
                                    Data: 'acquisition_order_paystages',
                                    Condition: `Acquisition_Order_SerialNumber='${condSafeOrder}' AND Stage_Name='${stgName.replace(/'/g,"''")}'`
                                });
                                fullStageRow = Array.isArray(fbArr) ? fbArr[0] : (fbArr && fbArr.Data && fbArr.Data[0]);
                            } catch (e3) { /* ignore */ }
                        }
                        if (fullStageRow) {
                            fullStageRow.Receipt_Ship_Status = shouldGray ? '1' : '0';
                            const nowRec = getYMDHMSDate();
                            const creatorRec = $.cookie('user') || $.cookie('enterprise') || '';
                            fullStageRow.Operation_ID = creatorRec;
                            fullStageRow.Operation_Datetime = nowRec;
                            if (!dataset.Modify['acquisition_order_paystages']) dataset.Modify['acquisition_order_paystages'] = [];
                            dataset.Modify['acquisition_order_paystages'].push(fullStageRow);
                        }
                    }
                } catch (e) { /* 查询失败不阻塞保存 */ }

                this.receiveSaving = true;
                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                try { console.log('buyer onConfirmReceive save result', res); } catch (e) {}

                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('已确认收货并保存入库记录');
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                    return;
                }
            } catch (e) { this.$message.error('收货保存失败'); }
            finally { this.receiveSaving = false; this.dialogReceiveVisible = false; this.getList(); }
        },
        // 构建 purchase_receipt 与明细结构
        getConfirmReceive(Receipt_Quantitys, Purchase_Order_SerialNumber, Article_SerialNumber, Receipt_Quantity, Receipt_Related_Number) {
            return [{
                Receipt_Date: getYMDHMSDate(),
                Receipt_Type: '0', // 仓库
                Receipt_Quantitys: Receipt_Quantitys, // 交易数量
                Enterprise_Info_SerialNumber: getCookie('enterprise'),
                Children: {
                    purchase_receipt_detail: [{
                        Purchase_Order_SerialNumber: Purchase_Order_SerialNumber, // 交易单号（买方：Acquisition_Order_SerialNumber）
                        Article_SerialNumber: Article_SerialNumber, // 商品流水号
                        Receipt_Quantity: Receipt_Quantity, // 入库数量
                        Receipt_Related_Number: Receipt_Related_Number || '', // 收货凭证
                        Enterprise_Info_SerialNumber: getCookie('enterprise'),
                    }]
                }
            }];
        },
        

        // 汇总（买方视角：付款/收货）
        getOrderSummary(row) {
            const toNum = v => { if (v === null || v === undefined || v === '') return 0; const n = Number(v); return isNaN(n) ? 0 : n; };
            return [
                { label: '付款', plan: toNum(row.Amount), done: toNum(row.Paid_Amount), remain: toNum(row.Remain_Amount) },
                { label: '收货', plan: toNum(row.Quantity), done: toNum(row.Receipt_Quantity), remain: toNum(row.Unreceipt_Quantity) }
            ];
        },

        // 返回到采购订单列表页
        handleBack() {
                window.location.href = '/view/transaction/purchase_order/index.html';
        },

        handlePageChange(p) { this.form.PageNumber = p; }
    }
});
